package com.shujia.spark.core

import org.apache.spark.rdd.RDD
import org.apache.spark.{SparkConf, SparkContext}

object Demo16Sort {
  def main(args: Array[String]): Unit = {
    val conf = new SparkConf()

    conf.setAppName("group")

    conf.setMaster("local")

    val sc = new SparkContext(conf)

    val linesRDD: RDD[String] = sc.textFile("data/score.txt")

    //取出学号和分数
    val scoreRDD: RDD[(String, Int)] = linesRDD
      .map(line => line.split(","))
      .filter(arr => arr.length == 3)
      .map {
        case Array(id: String, _: String, sco: String) =>
          (id, sco.toInt)
      }

    //计算总分
    val sumScoreRDD: RDD[(String, Int)] = scoreRDD.reduceByKey(_ + _)
    /**
      * sortBy: 指定一个字段进行排序
      * sortByKey;通过key进行排序
      * 默认是升序
      *
      */

    val sortByRDD: RDD[(String, Int)] = sumScoreRDD.sortBy(kv => kv._2, ascending = false)
    sortByRDD.foreach(println)

  }

}
